#include "myview.h"
#include <QMouseEvent>
#include <QWheelEvent>
#include <QScrollBar>

MyView::MyView(QWidget *parent) :
    QGraphicsView(parent)
{
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setRenderHint(QPainter::Antialiasing, true);
    this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
}

void MyView::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::MiddleButton) {
        m_lastMousePos = event->pos(); // 记录鼠标按下时的位置
    } else {
        mcurPt = mapToScene(event->pos());
    }
    QGraphicsView::mousePressEvent(event);
}

void MyView::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::MiddleButton) {
        // 计算鼠标移动的距离
        QPoint delta = event->pos() - m_lastMousePos;

        // 水平滚动条和垂直滚动条的值
        int horizontalValue = this->horizontalScrollBar()->value();
        int verticalValue = this->verticalScrollBar()->value();

        // 更新滚动条的值
        this->horizontalScrollBar()->setValue(horizontalValue - delta.x());
        this->verticalScrollBar()->setValue(verticalValue - delta.y());

        // 更新最后鼠标位置
        m_lastMousePos = event->pos();
    } else {
        QGraphicsView::mouseMoveEvent(event);
    }
}

void MyView::wheelEvent(QWheelEvent *event)
{
    // 计算缩放因子
    qreal scaleFactor = 1.15;
    if (event->angleDelta().y() > 0) {
        // 放大
        this->scale(scaleFactor, scaleFactor);
    } else {
        // 缩小
        this->scale(1.0 / scaleFactor, 1.0 / scaleFactor);
    }
}
